//
//  MessageInfoService.m
//  XTCloud
//
//  Created by QA on 16/10/8.
//  Copyright © 2016年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MessageInfoService.h"
#import "ServiceConnect.h"
#import "NSKeyedArchiverUserLogin.h"
#import "MessageInfoEntity.h"
#import "NSDictionary+DataFormat.h"

@implementation MessageInfoService

//获取消息保存到数据库
+ (void)getMessageInfoSaveToSqlite
{
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    if(!userInfo) return;
    NSString *userId = userInfo ? userInfo.Id : @"";
    
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:userId forKey:@"userId"];
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"Push_MessageList" dataArray:model];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        NSLog(@"[MessageInfoService] %@",@"Message Get Success");
        [self saveMessageInfoToSqlite:result.resultArray];
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"[MessageInfoService] Message Get Faild --%@",error);
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"[MessageInfoService] Message Get Faild --%@",error);
    }];
}

//改变用户未读消息状态
+ (void)changeMessageUnreadState:(NSString*)messageType
{
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    if(!userInfo) return;
    NSString *userId = userInfo ? userInfo.Id : @"";
    
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:userId forKey:@"userId"];
    [model setValue:messageType forKey:@"mesType"];
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"Push_MessageRead" dataArray:model];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        NSLog(@"[MessageInfoService] %@",@"Message Read State Change Success -Completed");
        
        //将该条消息标记为已读
        NSArray *findValue = [MessageInfoEntity MR_findByAttribute:@"onlyTag" withValue:messageType];
        if(findValue.count > 0){
            MessageInfoEntity *model = [findValue firstObject];
            model.readCount = 0;
            [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
        }
        
        //通知页面更新
        NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
        NSNotification *broadcastMessage = [NSNotification notificationWithName:MessageInfoServiceKey object:nil];
        [notificationCenter postNotification:broadcastMessage];
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"[MessageInfoService] Message Read State Faild --%@",error);
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"[MessageInfoService] Message Read State Faild --%@",error);
    }];
}

/**************************************************************************/

+ (void)saveMessageInfoToSqlite:(NSArray*)result
{
    //保存用户消息
    for(NSDictionary *temp in result){
        NSString *onlyTag = [temp objectFormatStringForKey:@"模块类型" defaults:@""];
        NSArray *findValue = [MessageInfoEntity MR_findByAttribute:@"onlyTag" withValue:onlyTag];
        
        //存在数据，就删除了再创建
        if(findValue.count > 0){
            MessageInfoEntity *model = [findValue firstObject];
            [model MR_deleteEntity];
        }
        
        MessageInfoEntity *person = [MessageInfoEntity MR_createEntity];
        person.icon = [temp objectFormatStringForKey:@"图标" defaults:@""];
        person.title = [temp objectFormatStringForKey:@"标题" defaults:@""];
        person.content = [temp objectFormatStringForKey:@"副标题" defaults:@""];
        person.readCount = [temp objectFormatIntegerNumberForKey:@"未读数量"];
        person.order = [temp objectFormatIntegerNumberForKey:@"排序"];
        person.onlyTag = [temp objectFormatStringForKey:@"模块类型" defaults:@""];
        
        //modelType类型：0异常、1原生、2网页
        //企业消息
        if([person.onlyTag isEqualToString:@"XX"]){
            person.createTime = [NSDate date];
            person.modelType = [NSNumber numberWithInteger:1];
            person.nativeCode = @"SJXMYYGL_XXTZ_QYTZ";
            person.webCode = @"";
        }
        
        //企业公文
        else if([person.onlyTag isEqualToString:@"GW"]){
            person.createTime = [NSDate date];
            person.modelType = [NSNumber numberWithInteger:1];
            person.nativeCode = @"SJXMYYGL_KSGN_WDDW";
            person.webCode = @"";
        }
        
        //审批流程
        else if([person.onlyTag isEqualToString:@"SP"]){
            person.createTime = [NSDate date];
            person.modelType = [NSNumber numberWithInteger:1];
            person.nativeCode = @"SJXMYYGL_KSGN_SP";
            person.webCode = @"";
        }
        
        //内部订单
        else if([person.onlyTag isEqualToString:@"DD"]){
            person.createTime = [NSDate date];
            person.modelType = [NSNumber numberWithInteger:1];
            person.nativeCode = @"SJXMYYGL_KSGN_NBXD";
            person.webCode = @"";
        }
        
        //外部订单
        else if([person.onlyTag isEqualToString:@"WDD"]){
            person.createTime = [NSDate date];
            person.modelType = [NSNumber numberWithInteger:1];
            person.nativeCode = @"SJXMYYGL_KSGN_WBXD";
            person.webCode = @"";
        }
        
        //手机浇筑令（中铁定制）
        else if([person.onlyTag isEqualToString:@"JZL"]){
            person.createTime = [NSDate date];
            person.modelType = [NSNumber numberWithInteger:1];
            person.nativeCode = @"CREC_SJXMYYGL_KSGN_NBXD";
            person.webCode = @"";
        }
        
        //未知类型处理
        else {
            person.createTime = [NSDate date];
            person.modelType = [NSNumber numberWithInteger:0];
            person.nativeCode = @"";
            person.webCode = @"";
        }
    }
    
    //APP图标标记
    NSInteger markNumber = 0;
    NSArray *valueArray = [MessageInfoEntity MR_findAll];
    for(MessageInfoEntity *entity in valueArray)
    markNumber += entity.readCount.integerValue;
    
    UIApplication *application = [UIApplication sharedApplication];
    [application setApplicationIconBadgeNumber:markNumber];
    
    //保存数据
    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
    
    //通知页面更新
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    NSNotification *broadcastMessage = [NSNotification notificationWithName:MessageInfoServiceKey object:nil];
    [notificationCenter postNotification:broadcastMessage];
}

//删除所有消息
+ (void)deleteALLEntity
{
    NSArray *persons = [MessageInfoEntity MR_findAll];
    for(MessageInfoEntity *model in persons) [model MR_deleteEntity];
        
    //对象销毁
    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
}

    
@end



